产品开发的时候无法避免的就是在一个 UITableView
中, 包含多种样式的 cell
, 我们通常的做法如下:
1 2 3 4 5 6 7
| if (indexPath.row == 0) { } else if (indexPath.row == 1) { } else if (indexPath.row == 2) { } .....
|
这样的做法没有问题, 但是如果有很多种 cell
的话, 例如资料页, 当需要在第二和第三个 cell
之间插入一个 cell
的时候, 我们需要把数组添加一列, 然后把整个 if
改一遍, 如何避免 index
之间的耦合?
OK, 简单来说就是在数据模型
中添加一个标识, 数据的排列交给数组, 我们不判断当前是第几个, 只根据标识来确定放那种样式的cell
,
这样只有当增加新的样式的时候才会涉及到改 UI 部分的代码, 大部分情况我们只需要对数组进行排序即可, 而不必因为该数组, 从而再改 if
.
###下面来介绍一款专门为了解耦而写的第三方: HYTableViewSection
使用方法:
pod 'HYTableViewSection'
通过构建数据来实现布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| HYTableViewRow *row = [HYTableViewRow row:@{@"title":@"style1"}]; row.identifier = @"style1"; row.heightBlock = ^CGFloat{ return 100; // heightBlock 可以使用计算复杂高度, 或者直接使用 row.height }; [self.tableView.hy_section addRowModel:row atSection:0]; HYTableViewRow *row1 = [HYTableViewRow row:@{@"title":@"style2"}]; row1.identifier = @"style2"; row1.heightBlock = ^CGFloat{ return 150; }; [self.tableView.hy_section addRowModel:row1 atSection:0]; HYTableViewRow *row2 = [HYTableViewRow row:@{@"title":@"style3"}]; row2.identifier = @"style3"; row2.heightBlock = ^CGFloat{ return 80; }; [self.tableView.hy_section addRowModel:row2 atSection:1];
|
代理方法中使用技巧, 除了新增 style
几乎不会涉及改 UITableView
的代理方法.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { HYTableViewRow *row = [self.tableView.hy_section modelAtIndexPath:indexPath]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:row.identifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:row.identifier]; } cell.textLabel.text = row.model[@"title"]; if ([row.identifier isEqualToString:@"style1"]) { cell.contentView.backgroundColor = [UIColor redColor]; } else if ([row.identifier isEqualToString:@"style2"]) { cell.contentView.backgroundColor = [UIColor greenColor]; } else if ([row.identifier isEqualToString:@"style3"]) { cell.contentView.backgroundColor = [UIColor blueColor]; } return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { HYTableViewRow *row = [self.tableView.hy_section modelAtIndexPath:indexPath]; return row.height; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.tableView.hy_section numberOfRowsInSection:section]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.tableView.hy_section numberOfSections]; }
|